using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 消息类型枚举
    /// </summary>
    public enum MessageType
    {
        Text,
        Voice,
        Image,
        Video,
        Emoji
    }
    /// <summary>
    /// 聊天消息模型
    /// </summary>
    public partial class ChatMessage : ObservableObject
    {
        /// <summary>
        /// 消息唯一标识符
        /// </summary>
        [ObservableProperty]
        private string _id = Guid.NewGuid().ToString();

        /// <summary>
        /// 消息内容
        /// </summary>
        [ObservableProperty]
        private string _content = string.Empty;

        /// <summary>
        /// 是否为用户发送的消息
        /// </summary>
        [ObservableProperty]
        private bool _isFromUser = true;

        /// <summary>
        /// 消息时间戳
        /// </summary>
        [ObservableProperty]
        private DateTime _timestamp = DateTime.Now;

        /// <summary>
        /// 发送者名称
        /// </summary>
        [ObservableProperty]
        private string _senderName = string.Empty;

        /// <summary>
        /// 发送者头像
        /// </summary>
        [ObservableProperty]
        private string _avatar = string.Empty;

        /// <summary>
        /// 消息类型
        /// </summary>
        [ObservableProperty]
        private MessageType _messageType = MessageType.Text;

        /// <summary>
        /// 语音消息时长（秒）
        /// </summary>
        [ObservableProperty]
        private int _voiceDuration = 0;

        /// <summary>
        /// 格式化的时间文本
        /// </summary>
        public string TimeText => Timestamp.ToString("HH:mm");

        /// <summary>
        /// 消息对齐方式（用户消息右对齐，其他消息左对齐）
        /// </summary>
        public LayoutOptions HorizontalOptions => IsFromUser ? LayoutOptions.End : LayoutOptions.Start;

        /// <summary>
        /// 头像列位置
        /// </summary>
        public int AvatarColumn => IsFromUser ? 2 : 0;

        /// <summary>
        /// 消息背景色
        /// </summary>
        public Color BackgroundColor => IsFromUser ? Color.FromArgb("#95EC69") : Color.FromArgb("#FFFFFF");

        /// <summary>
        /// 消息文本颜色
        /// </summary>
        public Color TextColor => IsFromUser ? Color.FromArgb("#000000") : Color.FromArgb("#000000");

        /// <summary>
        /// 是否为文本消息
        /// </summary>
        public bool IsTextMessage => MessageType == MessageType.Text;

        /// <summary>
        /// 是否为语音消息
        /// </summary>
        public bool IsVoiceMessage => MessageType == MessageType.Voice;

        /// <summary>
        /// 是否为表情消息
        /// </summary>
        public bool IsEmojiMessage => MessageType == MessageType.Emoji;

        /// <summary>
        /// 是否为视频消息
        /// </summary>
        public bool IsVideoMessage => MessageType == MessageType.Video;

        /// <summary>
        /// 是否为时间戳消息（用于居中显示时间）
        /// </summary>
        public bool IsTimeStamp => Content.Contains("月") || Content.Contains("昨天") || Content.Contains("今天");

        /// <summary>
        /// 是否不是时间戳消息
        /// </summary>
        public bool IsNotTimeStamp => !IsTimeStamp;

        /// <summary>
        /// 语音时长文本
        /// </summary>
        public string VoiceDurationText => $"{VoiceDuration}\"";
    }

    /// <summary>
    /// 聊天页面ViewModel
    /// </summary>
    public partial class ChatViewModel : BaseViewModel
    {
        /// <summary>
        /// 聊天消息集合
        /// </summary>
        [ObservableProperty]
        private ObservableCollection<ChatMessage> _messages = new();

        /// <summary>
        /// 当前输入的消息
        /// </summary>
        [ObservableProperty]
        private string _currentMessage = string.Empty;

        /// <summary>
        /// 当前用户名称
        /// </summary>
        [ObservableProperty]
        private string _currentUserName = "我";

        /// <summary>
        /// 机器人名称
        /// </summary>
        [ObservableProperty]
        private string _botName = "AI助手";

        /// <summary>
        /// 是否正在输入
        /// </summary>
        [ObservableProperty]
        private bool _isTyping = false;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ChatViewModel()
        {
           // 添加欢迎消息
            AddWelcomeMessage();
        }

        /// <summary>
        /// 发送消息命令
        /// </summary>
        [RelayCommand]
        private async Task SendMessage()
        {
            if (string.IsNullOrWhiteSpace(CurrentMessage))
                return;

            var userMessage = new ChatMessage
            {
                Content = CurrentMessage.Trim(),
                IsFromUser = true,
                SenderName = CurrentUserName,
                Avatar = "👤",
                Timestamp = DateTime.Now
            };

            // 添加用户消息
            Messages.Add(userMessage);

            // 清空输入框
            var messageToProcess = CurrentMessage.Trim();
            CurrentMessage = string.Empty;

            // 滚动到底部
            await ScrollToBottom();

            // 模拟机器人回复
            await SimulateBotReply(messageToProcess);
        }

        /// <summary>
        /// 模拟机器人回复
        /// </summary>
        private async Task SimulateBotReply(string userMessage)
        {
            IsTyping = true;

            // 模拟思考时间
            await Task.Delay(1000);

            var botReply = GenerateBotReply(userMessage);
            var botMessage = new ChatMessage
            {
                Content = botReply,
                IsFromUser = false,
                SenderName = BotName,
                Avatar = "🤖",
                Timestamp = DateTime.Now
            };

            Messages.Add(botMessage);
            IsTyping = false;

            // 滚动到底部
            await ScrollToBottom();
        }

        /// <summary>
        /// 生成机器人回复
        /// </summary>
        private string GenerateBotReply(string userMessage)
        {
            var lowerMessage = userMessage.ToLower();

            if (lowerMessage.Contains("你好") || lowerMessage.Contains("hello") || lowerMessage.Contains("hi"))
            {
                return "你好！很高兴与你聊天！有什么我可以帮助你的吗？";
            }
            else if (lowerMessage.Contains("时间") || lowerMessage.Contains("几点"))
            {
                return $"现在是 {DateTime.Now:yyyy年MM月dd日 HH:mm:ss}";
            }
            else if (lowerMessage.Contains("天气"))
            {
                return "抱歉，我暂时无法获取实时天气信息。你可以查看天气应用获取准确的天气预报。";
            }
            else if (lowerMessage.Contains("帮助") || lowerMessage.Contains("help"))
            {
                return "我是一个简单的AI助手，可以和你进行基本对话。你可以问我时间、打招呼或者随便聊聊！";
            }
            else if (lowerMessage.Contains("再见") || lowerMessage.Contains("bye"))
            {
                return "再见！期待下次与你聊天！";
            }
            else
            {
                var responses = new[]
                {
                    "这很有趣！能告诉我更多吗？",
                    "我明白了，还有其他想聊的吗？",
                    "听起来不错！你觉得怎么样？",
                    "这个话题很有意思呢！",
                    "谢谢你的分享！还有什么想说的吗？",
                    "我正在学习中，感谢你的耐心！"
                };
                
                var random = new Random();
                return responses[random.Next(responses.Length)];
            }
        }

        /// <summary>
        /// 添加欢迎消息
        /// </summary>
        private void AddWelcomeMessage()
        {
            // 添加时间戳消息
            var timeMessage = new ChatMessage
            {
                Content = "9月7日 11:26",
                IsFromUser = false,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddHours(-5)
            };
            Messages.Add(timeMessage);

            // 添加视频消息示例
            var videoMessage = new ChatMessage
            {
                Content = "0:55",
                IsFromUser = false,
                MessageType = MessageType.Video,
                Timestamp = DateTime.Now.AddHours(-5)
            };
            Messages.Add(videoMessage);

            // 添加时间戳
            var timeMessage2 = new ChatMessage
            {
                Content = "9月7日 12:43",
                IsFromUser = false,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddHours(-4)
            };
            Messages.Add(timeMessage2);

            // 添加表情消息
            var emojiMessage = new ChatMessage
            {
                Content = "👍👍👍",
                IsFromUser = false,
                MessageType = MessageType.Emoji,
                Timestamp = DateTime.Now.AddHours(-4)
            };
            Messages.Add(emojiMessage);

            // 添加时间戳
            var timeMessage3 = new ChatMessage
            {
                Content = "9月28日 21:01",
                IsFromUser = false,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddMinutes(-30)
            };
            Messages.Add(timeMessage3);

            // 添加用户文本消息
            var userMessage1 = new ChatMessage
            {
                Content = "把我姐夫过来的那个OPPO手机的抖音和红果果面的卡打了",
                IsFromUser = true,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddMinutes(-30)
            };
            Messages.Add(userMessage1);

            var userMessage2 = new ChatMessage
            {
                Content = "回去先打开",
                IsFromUser = true,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddMinutes(-29)
            };
            Messages.Add(userMessage2);

            var userMessage3 = new ChatMessage
            {
                Content = "抖音和红果短剧",
                IsFromUser = true,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddMinutes(-28)
            };
            Messages.Add(userMessage3);

            var userMessage4 = new ChatMessage
            {
                Content = "抖音和红果短剧",
                IsFromUser = true,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddMinutes(-27)
            };
            Messages.Add(userMessage4);

            // 添加时间戳
            var timeMessage4 = new ChatMessage
            {
                Content = "昨天 21:49",
                IsFromUser = false,
                MessageType = MessageType.Text,
                Timestamp = DateTime.Now.AddMinutes(-10)
            };
            Messages.Add(timeMessage4);

            // 添加语音消息
            var voiceMessage = new ChatMessage
            {
                Content = "通话时长 00:12 秒",
                IsFromUser = true,
                MessageType = MessageType.Voice,
                VoiceDuration = 12,
                Timestamp = DateTime.Now.AddMinutes(-10)
            };
            Messages.Add(voiceMessage);
        }

        /// <summary>
        /// 滚动到底部
        /// </summary>
        private async Task ScrollToBottom()
        {
            // 这里可以通过事件或者其他方式通知View滚动到底部
            await Task.Delay(100);
        }

        /// <summary>
        /// 清空聊天记录命令
        /// </summary>
        [RelayCommand]
        private async Task ClearMessages()
        {
            var result = await Shell.Current.DisplayAlert("确认", "确定要清空所有聊天记录吗？", "确定", "取消");
            if (result)
            {
                Messages.Clear();
                AddWelcomeMessage();
            }
        }
    }
}